package com.ztom.daily.n2022.m3;

import org.w3c.dom.Node;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * N 叉树的前序遍历
 * <p>
 * https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
 *
 * @author ZhangTao
 */
public class Day10Preorder {

    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    public List<Integer> preorder1(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        process(root, res);

        return res;
    }

    private void process(Node node, List<Integer> res) {
        if (node == null) {
            return;
        }

        res.add(node.val);
        for (Node child : node.children) {
            process(child, res);
        }
    }

    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Deque<Node> stack = new LinkedList<>();
        stack.addLast(root);
        Node node = null;
        while (!stack.isEmpty()) {
            node = stack.pollLast();
            res.add(node.val);
            for (int i = node.children.size() - 1; i >= 0; i--) {
                stack.addLast(node.children.get(i));
            }
        }

        return res;
    }
}
